<template>
  <div class="home-container">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <div class="logo-container">
            <el-icon class="logo-icon"><Trophy /></el-icon>
            <h2>在线知识竞赛系统</h2>
          </div>
        </div>
        <div class="header-right">
          <span class="welcome" v-if="userInfo">欢迎您，{{ userInfo.nickname }}</span>
          <el-button type="danger" plain round @click="handleLogout">退出登录</el-button>
        </div>
      </el-header>
      
      <el-container class="main-container">
        <!-- 左侧菜单栏 -->
        <el-aside width="240px" class="sidebar">
          <div class="user-info">
            <el-avatar :size="64" :src="userAvatar">{{ userInitial }}</el-avatar>
            <div class="user-detail">
              <div class="user-name">{{ userInfo?.nickname || '用户' }}</div>
              <div class="user-role">{{ userRoleText }}</div>
            </div>
          </div>
          
          <el-divider />
          
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            router
            background-color="#fff"
            text-color="#2c3e50"
            active-text-color="#409EFF"
          >
            <el-menu-item index="/home">
              <el-icon><HomeFilled /></el-icon>
              <span>首页</span>
            </el-menu-item>
            
            <el-menu-item index="/contest/list">
              <el-icon><Trophy /></el-icon>
              <span>竞赛广场</span>
            </el-menu-item>
            
            <el-sub-menu v-if="isInitiator || isAdmin" index="contest-manage">
              <template #title>
                <el-icon><Management /></el-icon>
                <span>竞赛管理</span>
              </template>
              <el-menu-item index="/contest/create">创建竞赛</el-menu-item>
              <el-menu-item index="/contest/manage">我的竞赛</el-menu-item>
            </el-sub-menu>
            
            <el-menu-item index="/profile">
              <el-icon><User /></el-icon>
              <span>个人中心</span>
            </el-menu-item>
            
            <el-sub-menu v-if="isAdmin" index="admin">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>系统管理</span>
              </template>
              <el-menu-item index="/admin/users">用户管理</el-menu-item>
              <el-menu-item index="/admin/contests">竞赛审核</el-menu-item>
              <el-menu-item index="/admin/statistics">系统统计</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        
        <el-main class="main-content">
          <!-- 角色信息提示 -->
          <el-row :gutter="20">
            <el-col :span="24">
              <div v-if="isAdmin" class="admin-info">
                <el-alert
                  title="您当前以管理员身份登录，可以访问系统管理功能"
                  type="success"
                  :closable="false"
                  effect="light"
                />
              </div>
              <div v-else-if="isInitiator" class="role-info">
                <el-alert
                  title="您当前以发起人身份登录"
                  type="info"
                  :closable="false"
                  effect="light"
                />
              </div>
              <div v-else-if="isContestant" class="role-info">
                <el-alert
                  title="您当前以参赛者身份登录"
                  type="info"
                  :closable="false"
                  effect="light"
                />
              </div>
            </el-col>
          </el-row>
          
          <!-- 功能概览 -->
          <el-row :gutter="20" class="dashboard-cards">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <el-icon class="stat-icon contest-icon"><TrendCharts /></el-icon>
                  <div class="stat-info">
                    <div class="stat-value">{{ stats.contestCount }}</div>
                    <div class="stat-label">可参与竞赛</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <el-icon class="stat-icon ranking-icon"><Medal /></el-icon>
                  <div class="stat-info">
                    <div class="stat-value">{{ stats.participatedCount }}</div>
                    <div class="stat-label">已参与竞赛</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <el-icon class="stat-icon score-icon"><DataAnalysis /></el-icon>
                  <div class="stat-info">
                    <div class="stat-value">{{ stats.rankScore }}</div>
                    <div class="stat-label">我的积分</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <el-icon class="stat-icon cert-icon"><Document /></el-icon>
                  <div class="stat-info">
                    <div class="stat-value">{{ stats.certificateCount }}</div>
                    <div class="stat-label">获得证书</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 近期竞赛 -->
          <el-row>
            <el-col :span="24">
              <div class="section-header">
                <h3>近期竞赛</h3>
                <el-button type="primary" plain size="small" @click="goToContestList">查看全部</el-button>
              </div>
              
              <el-table :data="recentContests" style="width: 100%" v-loading="loading">
                <el-table-column prop="title" label="竞赛名称" min-width="180" />
                <el-table-column prop="startTime" label="开始时间" width="160" :formatter="formatDate" />
                <el-table-column prop="currentParticipants" label="参与人数" width="100" align="center" />
                <el-table-column label="状态" width="100" align="center">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)" size="small">
                      {{ getStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                  <template #default="scope">
                    <el-button type="primary" link size="small" @click="viewContestDetail(scope.row.id)">
                      查看
                    </el-button>
                    <el-button 
                      v-if="canJoinContest(scope.row)" 
                      type="success" 
                      link 
                      size="small" 
                      @click="joinContest(scope.row.id)"
                    >
                      参与
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
      
      <el-footer class="footer">
        <p>© {{ new Date().getFullYear() }} 在线知识竞赛系统 版权所有</p>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserInfo } from '@/api/user'
import { getContestList } from '@/api/contest'
import { 
  Setting, 
  User, 
  Trophy, 
  Management, 
  HomeFilled, 
  Medal, 
  TrendCharts, 
  DataAnalysis, 
  Document
} from '@element-plus/icons-vue'

export default {
  name: 'HomeView',
  components: {
    Setting,
    User,
    Trophy,
    Management,
    HomeFilled,
    Medal,
    TrendCharts,
    DataAnalysis,
    Document
  },
  setup() {
    const router = useRouter()
    const userInfo = ref(null)
    const activeMenu = ref('/home')
    const loading = ref(false)
    const recentContests = ref([])
    
    // 用户统计数据（示例数据）
    const stats = ref({
      contestCount: 0,
      participatedCount: 0,
      rankScore: 0,
      certificateCount: 0
    })

    // 获取用户头像首字母
    const userInitial = computed(() => {
      if (userInfo.value && userInfo.value.nickname) {
        return userInfo.value.nickname.substring(0, 1).toUpperCase()
      }
      return 'U'
    })

    // 获取用户头像
    const userAvatar = computed(() => {
      return userInfo.value?.avatar || ''
    })

    // 判断是否是管理员
    const isAdmin = computed(() => {
      return userInfo.value && userInfo.value.roleCode === 'ADMIN'
    })

    // 判断是否是发起人
    const isInitiator = computed(() => {
      return userInfo.value && userInfo.value.roleCode === 'INITIATOR'
    })

    // 判断是否是参赛者
    const isContestant = computed(() => {
      return userInfo.value && userInfo.value.roleCode === 'CONTESTANT'
    })

    // 获取用户角色文本
    const userRoleText = computed(() => {
      if (isAdmin.value) return '管理员'
      if (isInitiator.value) return '竞赛发起人'
      if (isContestant.value) return '竞赛参与者'
      return '普通用户'
    })
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        // 先从localStorage获取用户信息
        const cachedUserInfo = localStorage.getItem('userInfo')
        if (cachedUserInfo) {
          userInfo.value = JSON.parse(cachedUserInfo)
          return
        }
        
        const res = await getUserInfo()
        userInfo.value = res.data
        // 缓存用户信息到localStorage
        localStorage.setItem('userInfo', JSON.stringify(res.data))
      } catch (error) {
        console.error('获取用户信息失败', error)
      }
    }
    
    // 获取近期竞赛
    const fetchRecentContests = async () => {
      loading.value = true
      try {
        const res = await getContestList({
          page: 1,
          size: 5,
          status: 1 // 进行中的竞赛
        })
        recentContests.value = res.data.records
        stats.value.contestCount = res.data.total
      } catch (error) {
        console.error('获取竞赛列表失败', error)
      } finally {
        loading.value = false
      }
    }
    
    // 模拟获取用户统计数据
    const fetchUserStats = () => {
      // 实际项目中这里应该调用API获取真实数据
      stats.value = {
        contestCount: 12,
        participatedCount: 5,
        rankScore: 320,
        certificateCount: 2
      }
    }
    
    // 退出登录
    const handleLogout = () => {
      ElMessageBox.confirm(
        '确定要退出登录吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        ElMessage.success('已退出登录')
        router.push('/login')
      }).catch(() => {})
    }
    
    // 格式化日期
    const formatDate = (row) => {
      if (!row.startTime) return '未设置'
      const date = new Date(row.startTime)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '待审核'
        case 1: return '进行中'
        case 2: return '已拒绝'
        case 3: return '已取消'
        case 4: return '已结束'
        default: return '未知状态'
      }
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case 0: return 'warning'
        case 1: return 'success'
        case 2: return 'danger'
        case 3: return 'info'
        case 4: return 'primary'
        default: return 'info'
      }
    }
    
    // 是否可以参与竞赛
    const canJoinContest = (contest) => {
      return contest.status === 1 && 
        (!contest.participantLimit || contest.currentParticipants < contest.participantLimit)
    }
    
    // 查看竞赛详情
    const viewContestDetail = (id) => {
      router.push(`/contest/detail/${id}`)
    }
    
    // 参与竞赛
    const joinContest = (id) => {
      router.push(`/contest/detail/${id}`)
    }
    
    // 进入竞赛广场
    const goToContestList = () => {
      router.push('/contest/list')
    }
    
    onMounted(() => {
      fetchUserInfo()
      fetchRecentContests()
      fetchUserStats()
    })
    
    return {
      userInfo,
      userInitial,
      userAvatar,
      activeMenu,
      loading,
      recentContests,
      stats,
      isAdmin,
      isInitiator,
      isContestant,
      userRoleText,
      handleLogout,
      formatDate,
      getStatusText,
      getStatusType,
      canJoinContest,
      viewContestDetail,
      joinContest,
      goToContestList
    }
  }
}
</script>

<style lang="scss" scoped>
.home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  
  .header {
    background: linear-gradient(90deg, #3a7bd5, #00d2ff);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    height: 60px;
    
    .header-left {
      .logo-container {
        display: flex;
        align-items: center;
        
        .logo-icon {
          font-size: 24px;
          margin-right: 10px;
        }
        
        h2 {
          margin: 0;
          font-size: 20px;
          font-weight: 600;
        }
      }
    }
    
    .header-right {
      display: flex;
      align-items: center;
      
      .welcome {
        margin-right: 15px;
        font-size: 14px;
      }
    }
  }
  
  .main-container {
    flex: 1;
    overflow: hidden;
    
    .sidebar {
      background-color: #fff;
      border-right: 1px solid #e6e6e6;
      box-shadow: 2px 0 8px rgba(0, 0, 0, 0.03);
      height: 100%;
      
      .user-info {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px 10px;
        
        .el-avatar {
          margin-bottom: 10px;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .user-detail {
          text-align: center;
          
          .user-name {
            font-size: 16px;
            font-weight: 500;
            color: #2c3e50;
            margin-bottom: 4px;
          }
          
          .user-role {
            font-size: 12px;
            color: #909399;
          }
        }
      }
      
      .sidebar-menu {
        border-right: none;
        
        .el-menu-item, .el-sub-menu__title {
          height: 50px;
          line-height: 50px;
        }
        
        .el-icon {
          margin-right: 5px;
        }
      }
    }
    
    .main-content {
      background-color: #f5f7fa;
      padding: 20px;
      overflow-y: auto;
      
      .admin-info, .role-info {
        margin-bottom: 20px;
      }
      
      .dashboard-cards {
        margin-bottom: 20px;
        
        .stat-card {
          margin-bottom: 20px;
          border-radius: 8px;
          
          .stat-content {
            display: flex;
            align-items: center;
            
            .stat-icon {
              font-size: 40px;
              margin-right: 15px;
              
              &.contest-icon {
                color: #409eff;
              }
              
              &.ranking-icon {
                color: #67c23a;
              }
              
              &.score-icon {
                color: #e6a23c;
              }
              
              &.cert-icon {
                color: #f56c6c;
              }
            }
            
            .stat-info {
              .stat-value {
                font-size: 24px;
                font-weight: bold;
                color: #2c3e50;
                line-height: 1.2;
              }
              
              .stat-label {
                font-size: 14px;
                color: #909399;
              }
            }
          }
        }
      }
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        
        h3 {
          margin: 0;
          color: #2c3e50;
          font-size: 18px;
        }
      }
    }
  }
  
  .footer {
    background-color: #f5f7fa;
    text-align: center;
    color: #909399;
    font-size: 14px;
    border-top: 1px solid #e5e7eb;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style> 